<?php



// 2. AJAX Handler for Post Likes
// =============================================================================
function handle_post_like()
{
    check_ajax_referer('wanzicms_interactions_nonce', 'nonce');

    $post_id = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0;

    if ($post_id > 0) {
        $likes_count = (int) get_post_meta($post_id, '_post_likes_count', true);
        $new_likes_count = $likes_count + 1;
        update_post_meta($post_id, '_post_likes_count', $new_likes_count);

        // Set a cookie to prevent multiple likes from the same non-logged-in user
        // The cookie will expire in 1 year.
        $liked_posts_cookie = isset($_COOKIE['wanzicms_liked_posts']) ? json_decode(stripslashes($_COOKIE['wanzicms_liked_posts']), true) : [];
        if (!in_array($post_id, $liked_posts_cookie)) {
            $liked_posts_cookie[] = $post_id;
        }
        setcookie('wanzicms_liked_posts', json_encode($liked_posts_cookie), time() + YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN);

        wp_send_json_success(['likes' => $new_likes_count]);
    } else {
        wp_send_json_error('Invalid post ID.');
    }

    wp_die();
}
add_action('wp_ajax_nopriv_post_like', 'handle_post_like');
add_action('wp_ajax_post_like', 'handle_post_like');


// 3. AJAX Handler for Post Favorites (for logged-in users)
// =============================================================================
function handle_post_favorite()
{
    check_ajax_referer('wanzicms_interactions_nonce', 'nonce');

    if (!is_user_logged_in()) {
        wp_send_json_error(['message' => '请先登录']);
        wp_die();
    }

    $post_id = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0;
    $user_id = get_current_user_id();

    if ($post_id > 0 && $user_id > 0) {
        $favorites = get_user_meta($user_id, '_favorite_posts', true);
        if (!is_array($favorites)) {
            $favorites = [];
        }

        if (in_array($post_id, $favorites)) {
            // Remove from favorites
            $favorites = array_diff($favorites, [$post_id]);
            $status = 'unfavorited';
        } else {
            // Add to favorites
            $favorites[] = $post_id;
            $status = 'favorited';
        }

        update_user_meta($user_id, '_favorite_posts', $favorites);
        wp_send_json_success(['status' => $status]);
    } else {
        wp_send_json_error('Invalid data.');
    }

    wp_die();
}
add_action('wp_ajax_post_favorite', 'handle_post_favorite');


// 4. Helper function to check if a post is favorited by the current user
// =============================================================================
function is_post_favorited($post_id)
{
    if (!is_user_logged_in()) {
        return false;
    }
    $user_id = get_current_user_id();
    $favorites = get_user_meta($user_id, '_favorite_posts', true);
    return is_array($favorites) && in_array($post_id, $favorites);
}


// 5. Helper function to check if current user has liked a post (via cookie)
// =============================================================================
function has_user_liked_post($post_id) {
    if (is_user_logged_in()) {
        // For logged-in users, a more robust system (e.g., user meta) would be better.
        // For simplicity, we still rely on cookies here.
    }
    $liked_posts_cookie = isset($_COOKIE['wanzicms_liked_posts']) ? json_decode(stripslashes($_COOKIE['wanzicms_liked_posts']), true) : [];
    return is_array($liked_posts_cookie) && in_array($post_id, $liked_posts_cookie);
}



// 统计文章浏览量
function getPostViews($postID)
{
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if ($count == '') {
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return '0 次浏览';
    }
    return $count . ' 次浏览';
}

// 更新文章浏览量
function setPostViews($postID)
{
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if ($count == '') {
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '1');
    } else {
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
add_action('wp_head', 'setPostViews');


// 追踪用户阅读历史
function track_user_post_view() {
    if (is_single() && is_user_logged_in()) {
        $post_id = get_the_ID();
        $user_id = get_current_user_id();

        $read_posts = get_user_meta($user_id, '_read_posts', true);
        if (!is_array($read_posts)) {
            $read_posts = [];
        }

        if (!in_array($post_id, $read_posts)) {
            $read_posts[] = $post_id;
            update_user_meta($user_id, '_read_posts', $read_posts);
        }
    }
}
add_action('wp_head', 'track_user_post_view');


// 处理加载分类文章的 AJAX 请求
add_action('wp_ajax_nopriv_load_posts_by_term', 'load_posts_by_term');
add_action('wp_ajax_load_posts_by_term', 'load_posts_by_term');

function load_posts_by_term()
{
    $paged = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $term_id = isset($_GET['term_id']) ? intval($_GET['term_id']) : 0;
    $is_category = isset($_GET['is_category']);

    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 10,
        'paged' => $paged,
    );

    if ($term_id > 0) {
        if ($is_category) {
            $args['cat'] = $term_id;
        } else {
            $args['tag_id'] = $term_id;
        }
    }

    $query = new WP_Query($args);
    if ($query->have_posts()) {
        $list_style = wanzi_option('g_post_list_style', 'grid');
        $template_slug = 'content-' . $list_style;

        while ($query->have_posts()) {
            $query->the_post();
            get_template_part('template-parts/' . $template_slug);
        }
    }
    wp_die();
}
